package spring.cloud.tasks.executor.listener.task_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.listener.TreeCacheListener;
import spring.cloud.tasks.executor.utils.log.LogUtils;

/**
 * runOneTime operation.<br>
 * once triggered, delete the node.
 */
@Slf4j
@Setter
@Getter
class TriggerTaskRunAtOnceListener extends TreeCacheListener {

    private final TaskExecuteListenerHolder taskExecuteListener;

    public TriggerTaskRunAtOnceListener(TaskExecuteListenerHolder taskExecuteListener) {
        this.taskExecuteListener = taskExecuteListener;
    }

    @Override
    protected void dataChanged(final CuratorFramework curatorFramework, final String path, final TreeCacheEvent treeCacheEvent) {
        if (taskExecuteListener.isShutdown) {
            return;
        }
        if ((TreeCacheEvent.Type.NODE_ADDED == treeCacheEvent.getType() || TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType()) && ExecutorNode.isRunOneTimePath(taskExecuteListener.taskId, path, taskExecuteListener.executorId)) {
            if (!taskExecuteListener.taskExecutor.getTaskExecuteEngine().isRunning()) {

                LogUtils.info(log, taskExecuteListener.taskId, "job run-at-once triggered, triggeredData:{}");
                taskExecuteListener.taskExecutor.triggerTask();
            } else {
                LogUtils.info(log, taskExecuteListener.taskId, "job is running, run-at-once ignored.");
            }
            taskExecuteListener.zookeeper.delete(path);
        }
    }

}
